package com.zq.assistant.func.apifactory.handler;

import android.text.TextUtils;
import android.util.Log;

import com.squareup.okhttp.Response;
import com.zq.assistant.app.App;
import com.zq.assistant.func.apifactory.annotation.HttpMethod;
import com.zq.assistant.func.apifactory.annotation.Mode;
import com.zq.assistant.func.apifactory.api.LifeCycle;
import com.zq.assistant.func.apifactory.callback.FailureCallback;
import com.zq.assistant.func.apifactory.callback.ResultCallback;
import com.zq.assistant.func.apifactory.invocationhandler.HttpParam;
import com.zq.assistant.func.apifactory.invocationhandler.HttpRequest;
import com.zq.assistant.func.log.Logger;
import com.zq.assistant.utils.JsonUtils;
import com.zq.assistant.utils.NetWorkUtils;
import com.zq.assistant.utils.OKHttpUtils;
import com.zq.assistant.utils.ObjectCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * OKHttp处理器
 * Created by zhangqiang on 2016/8/4.
 */
public class OKHttpRequestHandler extends BaseOKHttpRequestHandler {

    @Override
    public Object onHandleHttpRequest(final HttpRequest httpRequest) {
        super.onHandleHttpRequest(httpRequest);

        ArrayList<HttpParam> httpParams = httpRequest.getParams();
        String requestURL = httpRequest.getUrl();
        Object tag = httpRequest.getTag();
        ResultCallback callback = httpRequest.getCallback();

        Logger.get().i("NetWork",httpRequest.toString());

        if (!NetWorkUtils.isNetWorkEnable(App.instance)) {

            if (callback != null) {
                callback.onFail(FailureCallback.NET_WORK_DISABLE, "net work disable");
            }
            return null;
        }

        if (httpRequest.getHttpMethod() == HttpMethod.GET) {

            if (httpParams != null && !httpParams.isEmpty()) {

                StringBuilder unEncodeParamSb = new StringBuilder();

                for (int i = 0; i < httpParams.size(); i++) {

                    HttpParam httpParam = httpParams.get(i);

                    unEncodeParamSb.append(httpParam.getKey());
                    unEncodeParamSb.append("=");
                    unEncodeParamSb.append(httpParam.getValue());
                    if (i != httpParams.size() - 1) {
                        unEncodeParamSb.append("&");
                    }
                }

                requestURL = requestURL + "?" + unEncodeParamSb;
            }


            if (httpRequest.getMode() == Mode.SYNC) {

                try {
                    return handleResponse(OKHttpUtils.getSync(requestURL,null, tag), httpRequest.getReturnClass(), httpRequest.getReturnGenericClass());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            } else if (httpRequest.getMode() == Mode.ASYNC) {

                if (callback != null) {

                    OKHttpUtils.get(requestURL,null, tag, new ObjectCallback(httpRequest.getCallbackGenericClass(), httpRequest.getCallbackGenericClass2(), callback));
                }
            }

            return null;
        } else if (httpRequest.getHttpMethod() == HttpMethod.POST) {

            if (httpParams != null && !httpParams.isEmpty()) {

                LinkedHashMap<String, Object> paramsMap = new LinkedHashMap<>();

                for (int i = 0; i < httpParams.size(); i++) {

                    HttpParam httpParam = httpParams.get(i);


                    paramsMap.put(httpParam.getKey(), httpParam.getValue());
                }

                String jsonParam = JsonUtils.toJsonString(paramsMap);
                if (httpRequest.getMode() == Mode.ASYNC) {

                    if (callback != null) {

                        OKHttpUtils.postJsonString(requestURL, jsonParam, tag,
                                new ObjectCallback(httpRequest.getCallbackGenericClass(), httpRequest.getCallbackGenericClass2(), callback));
                    }
                } else if (httpRequest.getMode() == Mode.SYNC) {

                    try {

                        return handleResponse(OKHttpUtils.postJsonStringSync(requestURL, jsonParam, tag), httpRequest.getReturnClass(), httpRequest.getReturnGenericClass());
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                    return null;
                }
            }
        }

        return null;
    }


    private Object handleResponse(Response response, Class<?> returnClass, Class<?> returnGenericClass) {

        if (response == null || !response.isSuccessful()) {
            return null;
        }

        try {

            String respString = response.body().string();

            Log.e("Http", "========Http result json==============" + respString);
            if (!TextUtils.isEmpty(respString)) {

                return JsonUtils.toObject(respString, returnClass, returnGenericClass);
            }
        } catch (Throwable t) {

            t.printStackTrace();
        }
        return null;
    }


    @Override
    public void cancel() {

        OKHttpUtils.cancel(getTag());
    }
}
